package com.example.administrator.newxlmedical;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseActivity;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import adapters.ReturnHintAdapter;
import beans.GoodsDetailInfoBean;
import beans.NewUserInfoBean;
import beans.ReturnHintBean;
import beans.UnusedGoodsBean;
import beans.UserInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import constants.HandlerConstant;
import dialogs.GoodsDetialsDialog;
import interfaces.MyItemClickListener;
import netframe.GetRetrofit;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import utils.ActivityUtil;
import utils.ObjectSaveUtil;
import utils.ReturnHintSortUtils;
import utils.TimeUtil;
import utils.ViewUtil;

public class ReturnHintActivity extends BaseActivity {

    @BindView(R.id.return_home)
    ImageView returnHome;
    @BindView(R.id.remind_title)
    RelativeLayout remindTitle;
    @BindView(R.id.rv_return_activity)
    RecyclerView recyclerView;
    @BindView(R.id.fl_return_empty)
    FrameLayout flEmpty;
    @BindView(R.id.return_ll)
    LinearLayout returnLl;
    @BindView(R.id.return_goods)
    TextView tvGoods;
    @BindView(R.id.iv_return_goods_sort)
    ImageView ivGoodsSort;
    @BindView(R.id.rl_return_goods_sort)
    RelativeLayout rlGoodsSort;
    @BindView(R.id.return_supplier)
    TextView tvSupplier;
    @BindView(R.id.iv_return_supplier_sort)
    ImageView ivSupplierSort;
    @BindView(R.id.rl_return_supplier_sort)
    RelativeLayout rlSupplierSort;
    @BindView(R.id.return_size)
    TextView tvSpecification;
    @BindView(R.id.iv_return_specification_sort)
    ImageView ivSpecificationSort;
    @BindView(R.id.rl_return_specification_sort)
    RelativeLayout rlSpecificationSort;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.iv_return_number_sort)
    ImageView ivNumberSort;
    @BindView(R.id.rl_return_number_sort)
    RelativeLayout rlNumberSort;
    @BindView(R.id.return_data_end)
    TextView tvOperator;
    @BindView(R.id.iv_return_operator_sort)
    ImageView ivOperatorSort;
    @BindView(R.id.rl_return_operator_sort)
    RelativeLayout rlOperatorSort;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.iv_return_time_sort)
    ImageView ivTimeSort;
    @BindView(R.id.rl_return_time_sort)
    RelativeLayout rlTimeSort;
    private ArrayAdapter<String> mAdapter;
    private String[] spinnerData = {"全部", "1", "2", "3", "4", "5"};
    private int mPosition;
    private SharedPreferences sharedPreferences;
    private ReturnHintAdapter adapter;
    private StringBuilder sbUserIds = new StringBuilder();

    private boolean isSortGoods, isSortSpecification, isSortSupplier, isSortNumebr, isSortOperator, isSortTime, isReturn, isNoReturn;
    private int sortGoods, sortSpecification, sortSupplier, sortNumber, sortTime, sortOperator;
    private List<ReturnHintBean> list = new ArrayList<>();
    private List<ReturnHintBean> sortlist = new ArrayList<>();
    private PopupWindow mPopupWindow;
    private NewUserInfoBean.DataBean bean;
    private boolean isLoading1;
    private boolean isLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_hint);
        ButterKnife.bind(this);
    }

    @Override
    public void initView() {
        super.initView();
        sharedPreferences = ActivityUtil.getSharedPreferences(this);
        bean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(this, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
        adapter = new ReturnHintAdapter(ReturnHintActivity.this, list);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        recyclerView.setVisibility(View.GONE);
        showLoadingView(flEmpty);
        loadingTask1(); // 未使用 （未超过24小时）
    }

    private void loadingTask1() {
        int id = bean.getID();
        int roleId = bean.getRoleInfoId();
        if (roleId == Constants.ROLE_HEAD_NURSE || roleId == Constants.ROLE_MANAGE || roleId == Constants.ROLE_FACTORY) {
            id = 0;
        }
        GetRetrofit.getInstance().getUnusedGoods(NetAddress.token, NetAddress.machineCode, NetAddress.deptCode, id + "", "1")
                .enqueue(new Callback<UnusedGoodsBean>() {
                    @Override
                    public void onResponse(Call<UnusedGoodsBean> call, Response<UnusedGoodsBean> response) {
                        sbUserIds.delete(0, sbUserIds.length());
                        UnusedGoodsBean data = response.body();

                        Map<String, ReturnHintBean> map = new HashMap();
                        if (data != null && data.getData() != null && data.getData().size() != 0) {
                            List<UnusedGoodsBean.DataBean> body = data.getData();
                            for (int i = 0; i < body.size(); i++) {
                                UnusedGoodsBean.DataBean unusedGoodsBean = body.get(i);
                                String idAndGid = unusedGoodsBean.getUserId() + "," + unusedGoodsBean.getGID() + unusedGoodsBean.getOutCabinetTime();

                                ReturnHintBean bean = new ReturnHintBean();
                                bean.setGoodsName(unusedGoodsBean.getGoodName());
                                bean.setSpecification(unusedGoodsBean.getSpecification());
                                bean.setManufacturer(unusedGoodsBean.getManufacturer());
                                bean.setTakeTime(TimeUtil.getTime(unusedGoodsBean.getOutCabinetTime()));
                                bean.setGID(unusedGoodsBean.getGID() + "");
                                bean.setID(unusedGoodsBean.getUserId() + "");
                                bean.setNoReturn(false);
                                bean.setUnit(unusedGoodsBean.getGoodsUnit());
                                bean.setOperator(unusedGoodsBean.getName());
                                if (map.get(idAndGid) != null) {
                                    ReturnHintBean returnHintBean = map.get(idAndGid);
                                    bean.setNumber((Integer.parseInt(returnHintBean.getNumber()) + 1 + ""));
                                    bean.getBarCode().addAll(returnHintBean.getBarCode());
                                }

                                // TODO: 接口没有 入柜时间
//                                String time;
//                                if (TextUtils.isEmpty(unusedGoodsBean.getReturnTime())){
//                                    time = TimeUtil.getNowTime(unusedGoodsBean.getIntoCabinetTime()).substring(0,19);
//                                }else {
//                                    time = TimeUtil.getNowTime(unusedGoodsBean.getReturnTime()).substring(0,19);
//                                }

                                bean.getBarCode().add(unusedGoodsBean.getBarCode());
                                map.put(idAndGid, bean);

                            }
                            Set set = map.entrySet();
                            Iterator iterator = set.iterator();
                            while (iterator.hasNext()) {
                                Map.Entry mapentry = (Map.Entry) iterator.next();
                                ReturnHintBean bean = (ReturnHintBean) mapentry.getValue();
                                sbUserIds.append("'" + bean.getID() + "',");
                                list.add(bean);
                            }
                        }
                        isLoading1 = true;
                        loadingTask();
                    }

                    @Override
                    public void onFailure(Call<UnusedGoodsBean> call, Throwable t) {
                        loadingTask();
                    }
                });
    }

    private void loadingTask() {
        int id = bean.getID();
        int roleId = bean.getRoleInfoId();
        if (roleId == Constants.ROLE_HEAD_NURSE || roleId == Constants.ROLE_MANAGE || roleId == Constants.ROLE_FACTORY) {
            id = 0;
        }
        GetRetrofit.getInstance().getUnusedGoods(NetAddress.token, NetAddress.machineCode, NetAddress.deptCode, id + "", "2")
                .enqueue(new Callback<UnusedGoodsBean>() {
                    @Override
                    public void onResponse(Call<UnusedGoodsBean> call, Response<UnusedGoodsBean> response) {
                        UnusedGoodsBean data = response.body();
                        if (data != null) {
                            List<UnusedGoodsBean.DataBean> body = data.getData();
                            Map<String, ReturnHintBean> map = new HashMap();
                            if (body != null && body.size() != 0) {
                                for (int i = 0; i < body.size(); i++) {
                                    UnusedGoodsBean.DataBean unusedGoodsBean = body.get(i);
                                    String idAndGid = unusedGoodsBean.getUserId() + "," + unusedGoodsBean.getGID();
                                    ReturnHintBean bean = new ReturnHintBean();
                                    bean.setGoodsName(unusedGoodsBean.getGoodName());
                                    bean.setSpecification(unusedGoodsBean.getSpecification());
                                    bean.setManufacturer(unusedGoodsBean.getManufacturer());
                                    bean.setTakeTime(TimeUtil.getTime(unusedGoodsBean.getOutCabinetTime()));
                                    bean.setGID(unusedGoodsBean.getGID() + "");
                                    bean.setID(unusedGoodsBean.getUserId() + "");
                                    bean.setUnit(unusedGoodsBean.getGoodsUnit());
                                    bean.setNoReturn(true);
                                    bean.setOperator(unusedGoodsBean.getName());
                                    if (map.get(idAndGid) != null) {
                                        ReturnHintBean returnHintBean = map.get(idAndGid);
                                        bean.setNumber((Integer.parseInt(returnHintBean.getNumber()) + 1 + ""));
                                        bean.getBarCode().addAll(returnHintBean.getBarCode());
                                    }
                                    bean.getBarCode().add(unusedGoodsBean.getBarCode());
                                    map.put(idAndGid, bean);

                                }
                                Set set = map.entrySet();
                                Iterator iterator = set.iterator();
                                while (iterator.hasNext()) {
                                    Map.Entry mapentry = (Map.Entry) iterator.next();
                                    ReturnHintBean bean = (ReturnHintBean) mapentry.getValue();
//                                    if (!sbUserIds.toString().contains(bean.getID())) {
//                                        sbUserIds.append("'" + bean.getID() + "',");
//                                    }
                                    list.add(bean);
                                }
                            }
                            if (list.size() > 0) {
//                                String userIds = sbUserIds.deleteCharAt(sbUserIds.length() - 1).toString();
//                                getUserInfo("select * from UserInfo where ID in (" + userIds + ")");
                                sortlist.clear();
                                sortlist.addAll(list);
                                recyclerView.setVisibility(View.VISIBLE);
                                adapter.notifyDataSetChanged();
                            } else {
                                showEmptyView(flEmpty);
                            }
                        }else {
                            showEmptyView(flEmpty);
                        }
                        hideLoadingView();
                    }

                    @Override
                    public void onFailure(Call<UnusedGoodsBean> call, Throwable t) {
                        hideLoadingView();
                        showEmptyView(flEmpty);
                    }
                });
    }

    private void getUserInfo(String sql) {
        Call<ArrayList<UserInfoBean>> call = GetRetrofit.getInstance().getUserInfo(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<ArrayList<UserInfoBean>>() {
            @Override
            public void onResponse(Call<ArrayList<UserInfoBean>> call, Response<ArrayList<UserInfoBean>> response) {
                ArrayList<UserInfoBean> body = response.body();
                if (body != null && body.size() != 0) {
                    for (int i = 0; i < body.size(); i++) {
                        UserInfoBean userInfoBean = body.get(i);
                        for (int j = 0; j < list.size(); j++) {
                            ReturnHintBean returnHintBean = list.get(j);
                            if (returnHintBean.getID().equals(userInfoBean.getID() + "")) {
                                list.get(j).setOperator(userInfoBean.getName());
                            }
                        }
                    }
                    sortlist.clear();
                    sortlist.addAll(list);
                    recyclerView.setVisibility(View.VISIBLE);
                    adapter.notifyDataSetChanged();
                } else {
                    showEmptyView(flEmpty);
                }
                hideLoadingView();
            }

            @Override
            public void onFailure(Call<ArrayList<UserInfoBean>> call, Throwable t) {

            }
        });
    }

    @Override
    protected void setListener() {
        super.setListener();

        adapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ReturnHintBean bean = list.get(position);

                GoodsDetailInfoBean infoBean = new GoodsDetailInfoBean();
                infoBean.setName(bean.getGoodsName());
                infoBean.setBarCode(bean.getBarCode());
                infoBean.setSpecification(bean.getSpecification());
                infoBean.setSupplier(bean.getManufacturer());
                infoBean.setTime(bean.getTakeTime());
                infoBean.setUnit(bean.getUnit());
                infoBean.setNumber(Integer.parseInt(bean.getNumber()));
                infoBean.setStatus(4);
                infoBean.setTimeName("取出时间 : ");
                infoBean.setOperator(bean.getOperator());

                infoBean.setTitle("未归提示");
                infoBean.setTitleContent("物品详情");

                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.GOODS_DETIAL_INFO,infoBean);
                Intent intent = new Intent(ReturnHintActivity.this, GoodsDetialActivity.class);
                intent.putExtra("bundle", bundle);
                startActivity(intent);

            }
        });
    }

    @OnClick({R.id.return_home, R.id.rl_return_goods_sort, R.id.rl_return_supplier_sort, R.id.rl_return_specification_sort,
            R.id.rl_return_number_sort, R.id.rl_return_operator_sort, R.id.rl_return_time_sort})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.return_home:
                finish();
                break;
            case R.id.rl_return_goods_sort:
                sort(1);
                break;
            case R.id.rl_return_supplier_sort:
                sort(2);
                break;
            case R.id.rl_return_specification_sort:
                sort(3);
                break;
            case R.id.rl_return_number_sort:
                sort(4);
                break;
            case R.id.rl_return_operator_sort:
                sort(5);
                break;
            case R.id.rl_return_time_sort:
                sort(6);
                break;
        }
    }

    private void sort(int type) {
        if (type == 1) { // 按物品名排序
            if (sortGoods != 2) {
                isSortGoods = !isSortGoods;
                sortGoods++;
                ReturnHintSortUtils.sortReturnHintGoods(list, isSortGoods);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortlist);
            }
        } else {
            sortGoods = 0;
            isSortGoods = false;
        }

        if (type == 2) { // 按供应商排序
            if (sortSupplier != 2) {
                isSortSupplier = !isSortSupplier;
                sortSupplier++;
                ReturnHintSortUtils.sortReturnHintSupplier(list, isSortSupplier);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortlist);
            }
        } else {
            sortSupplier = 0;
            isSortSupplier = false;
        }

        if (type == 3) {
            if (sortSpecification != 2) {
                isSortSpecification = !isSortSpecification;
                sortSpecification++;
                ReturnHintSortUtils.sortReturnHintSpecification(list, isSortSpecification);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortlist);
            }
        } else {
            sortSpecification = 0;
            isSortSpecification = false;
        }

        if (type == 4) {
            if (sortNumber != 2) {
                isSortNumebr = !isSortNumebr;
                sortNumber++;
                ReturnHintSortUtils.sortReturnHintNumber(list, isSortNumebr);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortlist);
            }
        } else {
            sortNumber = 0;
            isSortNumebr = false;
        }

        if (type == 5) {
            if (sortOperator != 2) {
                isSortOperator = !isSortOperator;
                sortOperator++;
                ReturnHintSortUtils.sortReturnHintOperator(list, isSortOperator);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortlist);
            }
        } else {
            sortOperator = 0;
            isSortOperator = false;
        }

        if (type == 6) {
            if (sortTime != 2) {
                isSortTime = !isSortTime;
                sortTime++;
                ReturnHintSortUtils.sortReturnHint(list, isSortTime);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(sortlist);
            }
        } else {
            sortTime = 0;
            isSortTime = false;
        }

        ViewUtil.setSortColor(this,tvGoods,ivGoodsSort,sortGoods);
        ViewUtil.setSortColor(this,tvSupplier,ivSupplierSort,sortSupplier);
        ViewUtil.setSortColor(this,tvOperator,ivOperatorSort,sortOperator);
        ViewUtil.setSortColor(this,tvSpecification,ivSpecificationSort,sortSpecification);
        ViewUtil.setSortColor(this,tvNumber,ivNumberSort,sortNumber);
        ViewUtil.setSortColor(this,tvTime,ivTimeSort,sortTime);

        adapter.notifyDataSetChanged();
    }

    private void clearSortDate(){
        sortGoods = 0;
        sortSupplier = 0;
        sortOperator = 0;
        sortTime = 0;
        sortSpecification = 0;
        sortNumber = 0;
    }

}